from kubernetes_asyncio import client

from balder.services.kube_base import KubeBase


class ServiceService(KubeBase):
    async def create_cluster_service(self, namespace: str, name: str, selector: dict, port: int, target_port: int, port_name: str = None) -> client.V1Service:
        # 通过 kubernetes 新建一个 service 资源
        service = client.V1Service(
            api_version="v1",
            kind="Service",
            metadata=client.V1ObjectMeta(name=name),
            spec=client.V1ServiceSpec(
                selector=selector,
                ports=[client.V1ServicePort(port=port, target_port=target_port, protocol="TCP", name=port_name)]
            ),
        )

        # 创建 service
        await self.core_v1_api.create_namespaced_service(namespace=namespace, body=service)

        return service

    async def delete_service(self, namespace: str, name: str) -> client.V1Status:
        # 通过 kubernetes 删除一个 service 资源
        return await self.core_v1_api.delete_namespaced_service(namespace=namespace, name=name, )

    async def get_service(self, namespace: str, name: str) -> client.V1Service:
        return await self.core_v1_api.read_namespaced_service(namespace=namespace, name=name)

    async def get_service_list(self, namespace: str) -> client.V1ServiceList:
        return await self.core_v1_api.list_namespaced_service(namespace=namespace)
